package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;


    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;


    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }



    /**
     * 入住申请
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //校验老人是否已经入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));
        if(elder != null){
            return;
        }
        //更新床位状态为已经入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 保存或更新老人数据
        Elder elder1 = insertOrupdate(dto.getCheckInElderDto(), bed);

        // 新增签约办理
        insertContract(elder1, dto);

        // 新增入住
        CheckIn checkIn = insertCheckIn(elder1, dto);

        // 新增入住配置
        insertCheckInConfig(checkIn, dto);
    }
    /**
     * 新增入住配置
     * @param checkIn
     * @param dto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住
     * @param elder
     * @param dto
     */

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param elder
     * @param dto
     */

    private void insertContract(Elder elder, CheckInApplyDto dto) {

        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        contract.setElderId(Integer.valueOf(elder.getId()+""));
        contract.setElderName(elder.getName());

        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(Long.valueOf(status));
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);

    }

    /**
     * 保存或更新老人数据
     * @param checkInElderDto
     */
    private Elder insertOrupdate(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        Elder oldelder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1));
        if(oldelder != null){
            elderMapper.updateById(elder);
        }else{
            elderMapper.insert(elder);
        }
        return  elder;

    }

    /**
     * 获取入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getDetail(Long id) {
        //查询入住信息  查询老人信息
        CheckIn checkIn=checkInMapper.selectCheckInById(id);
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, checkIn.getIdCardNo()));
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        String idCardNo = elder.getIdCardNo();
        String year= idCardNo.substring(6,10);//用substring截取身份证中的出生年份
        Integer last = Integer.valueOf(year);
        int now = LocalDate.now().getYear();
        checkInElderVo.setAge(now-last);

        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        checkInDetailVo.setContract(contract);
        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //转换家属列表
        List<ElderFamilyVo> familyList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(familyList);

        //整合数据返回
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }
}
